package com.itcast.springboot.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * @Author 郭泽鹏
 * @Date 2020/8/21 9:07
 * @Version 1.0
 * @Description 发送邮箱的工具类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component("sendMail")
public class SendMail {
    private String userEmail;

    private String subject;

    private String text;

    @Autowired
    private JavaMailSender mailSender;

    //发送者
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 绑定邮箱
     * @param userEmail 接收者
     * @param subject 邮件标题
     * @param text 邮件内容
     * @return 发送状态
     */
    public Boolean sendHtmlMail(String userEmail, String subject, String text){
        MimeMessage message=mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom(from);
            helper.setTo(userEmail);
            helper.setSubject(subject);
            helper.setText(text,true);      //是否是html格式的邮件
            mailSender.send(message);
        }catch (Exception e){
        }
        return Boolean.TRUE;
    }
}
